package net.onceface.application.impl;

import java.util.List;

import javax.inject.Named;

import org.springframework.transaction.annotation.Transactional;

import net.onceface.application.AddressApplication;
import net.onceface.application.assembler.AddressAssembler;
import net.onceface.application.commons.InvokeResult;
import net.onceface.application.dto.AddressDTO;
import net.onceface.core.domain.Address;
@Named
@Transactional
public class AddressApplicationImpl implements AddressApplication {

	@Override
	public List<AddressDTO> findByClientId(Long clientId) {
		return AddressAssembler.toDTOs(Address.findByClientId(clientId));
	}

	@Override
	public AddressDTO getByClientId(Long clientId) {
		return AddressAssembler.toDTO(Address.getByClientId(clientId));
	}

	@Override
	public InvokeResult edit(AddressDTO address) {
		
		AddressAssembler.toEntity(address).save();
		return InvokeResult.success();
	}

	@Override
	public InvokeResult setDef(Long id, Long clientId) {
		List<Address> addresses = Address.findByClientId(clientId);
		for(Address address : addresses){
			if(address.isDef()){
				address.setDef(false);
				address.save();
			}
			if(address.getId() == id){
				address.setDef(true);
				address.save();
			}
		}
		return InvokeResult.success();
	}

	@Override
	public InvokeResult remove(Long id) {
		Address address = Address.get(Address.class, id);
		address.remove();
		return InvokeResult.success();
	}

}
